/*
*  network interface operation
*  softwinner @ 2012-7-3 13:19:18
*
*/

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <cutils/properties.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include "cutils/misc.h"
#include "network.h"

#define LOG_TAG "RIL"
#include <utils/Log.h>
#include "sunxi_ril.h"

extern int ifc_init(void);
extern int ifc_close(void);
extern int ifc_get_info(const char *name, in_addr_t *addr, int *prefixLength, unsigned *flags);

// get the ip address of network interface
int get_interface_addr(const char* ifname, char* ipaddress)
{
	int ret = -1;
	unsigned myaddr = 0;
	
    if(NULL == ipaddress)
    {
		return ret;
	}
	
	ifc_init();
	ifc_get_info(ifname, &myaddr, NULL, NULL);
	if ( myaddr )
	{
		ret = 0;
		sprintf(ipaddress, "%d.%d.%d.%d", myaddr & 0xFF, (myaddr >> 8) & 0xFF, (myaddr >> 16) & 0xFF, (myaddr >> 24) & 0xFF);
		if(RIL_DEBUG)LOGD("ppp0 IP address is: %s!\n", ipaddress);
	}
	ifc_close();
	return ret;
}

// get pid by name
int get_pid(char *Name)
{
    char name[14] = {0};
    strncpy(name,Name,14);
	char szBuf[256] = {0}; 
	char cmd[20] = {0};
	char *p_pid = NULL;
	FILE *pFile = NULL;
	int  pid = 0;

	sprintf(cmd, "ps %s", name);
	pFile = popen(cmd, "r");
	if (pFile != NULL)
	{
		while (fgets(szBuf, sizeof(szBuf), pFile))  
		{  
			if(strstr(szBuf, name))
			{
				p_pid = strstr(szBuf, " "); 
				pid = strtoul(p_pid, NULL, 10);
				if(RIL_DEBUG) LOGD("--- pppd pid = %d ---",pid);
				break;
			}
		} 
	}
    pclose(pFile); 
    return pid;
}

// kill pppd,not by system("killall pppd &")
void kill_pppd()
{
    int pppd_pid = get_pid("pppd");
    int count = 5;

    if(pppd_pid)
	{
		kill(pppd_pid, SIGKILL);
		while (--count >= 0)
		{
			kill(pppd_pid, 0);
			if (errno == ESRCH)
			{
				break;
			}
			sleep(1);
		}
	}
}
